﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using MES.DataGateway.Common;
using log4net;
using Newtonsoft.Json;
using UFC.DBUtility;
using System.Collections;
using System.Data;

namespace SendIndustrialNetwork
{
    //MES与5厂（装配脉动线）排故信息接口
    public class SaveFiveDealFaultBillService
    {
        private ILog rsLog = LogHelp.receiveSave;
        public string fromAppId = ConfigurationManager.AppSettings["ToDataCenterAppID"].ToString();//推送数据中心来源ID
        public string toAppId_FIVE = ConfigurationManager.AppSettings["ToAppID_FIVE"].ToString();//推送数据中心目的ID（五厂）
        public string dataCenterHost = ConfigurationManager.AppSettings["dataCenterHost"].ToString();
        public string fileUploadUrl = "http://{0}:8080/lygkdc-service/lygk/dc/fileUploaddc";//文件上传地址
        public SaveFiveDealFaultBillService()
        {
            //fileUploadUrl = string.Format(fileUploadUrl, dataCenterHost);//文件上传地址
            fileUploadUrl = "http://localhost/LYMesApi/api/Default/fileUpload2";
            //LogHelp.SetConfig();
        }
        /// <summary>
        /// 数据处理（唯一对外方法）
        /// </summary>
        public void Excute()
        {
            DealFileData();
            //PushFiveDealFaultBillReceiveData();
            //PushFiveDealFaultBillStatusData();
            PushFiveDealFaultBillJsonData();
            SendToFiveProblemType(); //厂问题快反类型 add by zhangrj 20251105
        }

        #region 接收5厂排故信息
        void DealFileData()
        {
            string folderPath = ConfigurationManager.AppSettings["saveFilePath"].ToString();
            if (!Directory.Exists(folderPath)) return;
            // 获取指定路径下的所有文件（不包含子目录）
            string[] files = Directory.GetFiles(folderPath);
            // 遍历所有文件并输出文件名
            foreach (string file in files)
            {
                // 获取仅包含文件名（不含路径）
                string fileName = Path.GetFileName(file);
                if (!fileName.StartsWith("LYDL.PGFJ00")) continue;
                string filepath = folderPath + "\\" + fileName;
                string jsonData = File.ReadAllText(filepath).Trim();
                if (jsonData.ToString() == "")
                {
                    File.Delete(filepath);
                    continue;
                };
                if (fileName.StartsWith("LYDL.PGFJ001")) { DealFiveDealFaultBillData(jsonData, filepath); }
                if (fileName.StartsWith("LYDL.PGFJ002_R")) { DealFiveDealFaultBillFinishData(jsonData, filepath); }
            }
        }

        /// <summary>
        /// 处理5厂新建的排故信息
        /// </summary>
        public void DealFiveDealFaultBillData(string jsonData, string filepath)
        {
            try
            {
                rsLog.Info("MES开始处理五厂创建的排故JSON:【" + jsonData + "】");
                var json = JsonConvert.DeserializeObject(jsonData);
                var jsonObj2 = JsonConvert.DeserializeObject<Dictionary<string, object>>(json.ToString());
                var jsonObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonObj2["BSDATA"].ToString());
                var insertSQL = @"INSERT INTO DEALFAULTBILL(dealfaultbillid,dealfaultbillname,faultdesc,productbatchno,productname,returnfactoryid,createdate,createemployeeid,isuse,istransfer,repaircount,transferstatus,isreturn,dealfaulttype,dealfaultstatus,productandbatch,engineno,enginefamily,MilitaryCheckStatus,IsMilitaryCheck)
                                values('{0}','{1}','{2}','{3}','{4}',nvl((select factoryid from factory where factoryname='{5}'),'{5}'),to_date('{6}','yyyy-MM-dd hh24:mi:ss'),nvl((select employeeid from employee where employeename='{7}'),'{7}'),'{8}','{9}','{10}','{11}','{12}','{13}','{13}','{14}','{15}','{16}','{17}','{18}');";
                var insertSQL2 = @"INSERT INTO DEALFAULTBILLTRANSFER(DEALFAULTBILLID,AUDITEMPID,AUDITTIME,CONFIRMEMPID,CONFIRMTIME,fromempid,fromqty,fromtime,pagecount,requirefinishtime,Notes,pagecountfinish)
                                values('{0}',nvl((select employeeid from employee where employeename='{1}'),'{1}'),to_date('{2}','yyyy-MM-dd hh24:mi:ss'),nvl((select employeeid from employee where employeename='{3}'),'{3}'),to_date('{4}','yyyy-MM-dd hh24:mi:ss')
                                ,nvl((select employeeid from employee where employeename='{5}'),'{5}'),'{6}',to_date('{7}','yyyy-MM-dd hh24:mi:ss'),'{8}',to_date('{9}','yyyy-MM-dd hh24:mi:ss'),'{10}','{11}');";
                var updateSQL = @"update DEALFAULTBILL set faultdesc='{0}',productbatchno='{1}',productname='{2}',
                                returnfactoryid=nvl((select factoryid from factory where factoryname='{3}'),'{3}'),createdate=to_date('{4}','yyyy-MM-dd hh24:mi:ss'),
                                createemployeeid=nvl((select employeeid from employee where employeename='{5}'),'{5}'),istransfer='{6}',repaircount='{7}',transferstatus='{8}',isreturn='{9}',dealfaulttype='{10}',
                                dealfaultstatus='{10}',productandbatch='{11}',engineno='{12}',enginefamily='{13}',MilitaryCheckStatus='{14}',IsMilitaryCheck='{15}' where dealfaultbillid='{16}';";
                var updateSQL2 = @"update DEALFAULTBILLTRANSFER set AUDITEMPID=nvl((select employeeid from employee where employeename='{0}'),'{0}'),AUDITTIME=to_date('{1}','yyyy-MM-dd hh24:mi:ss'),
                                CONFIRMEMPID=nvl((select employeeid from employee where employeename='{2}'),'{2}'),CONFIRMTIME=to_date('{3}','yyyy-MM-dd hh24:mi:ss'),
                                fromempid=nvl((select employeeid from employee where employeename='{4}'),'{4}'),fromqty='{5}',fromtime=to_date('{6}','yyyy-MM-dd hh24:mi:ss'),pagecount='{7}',
                                requirefinishtime=to_date('{8}','yyyy-MM-dd hh24:mi:ss'),Notes='{9}',pagecountfinish='{10}' where dealfaultbillid='{11}';";
                var dt = OracleHelper.QueryTable(string.Format(@"select * from DEALFAULTBILL where dealfaultbillname='{0}' and isuse=0", jsonObj["DealFaultBillName"]), null);
                var allUpdate = @"begin {0} {1} end;";
                if (dt.Rows.Count > 0)
                {
                    updateSQL = string.Format(updateSQL, jsonObj["FaultDesc"], jsonObj["PRODUCTBATCHNO"], jsonObj["PRODUCTNAME"], jsonObj["RecvFactoryName"], jsonObj["CreateDate"],
                        jsonObj["CreateEmployee"], "0", jsonObj["RepairCount"], jsonObj["TransferStatus"], jsonObj["ISRETURN"], jsonObj["DealFaultType"], jsonObj["PRODUCTANDBATCH"], jsonObj["EngineNO"], jsonObj["EngineFamily"], jsonObj["MilitaryCheckStatus"], jsonObj["IsMilitaryCheck"], dt.Rows[0]["dealfaultbillid"]);
                    updateSQL2 = string.Format(updateSQL2, jsonObj["AuditempName"], jsonObj["audittime"], jsonObj["confirmempName"], jsonObj["confirmtime"], jsonObj["FromEmpName"], jsonObj["FromQty"], jsonObj["FromTime"], jsonObj["PageCount"], jsonObj["RequireFinishTime"], jsonObj["Notes"], jsonObj["pagecountfinish"], dt.Rows[0]["dealfaultbillid"]);
                    allUpdate = string.Format(allUpdate, updateSQL, updateSQL2);
                }
                else
                {
                    var uuid = Guid.NewGuid().ToString();
                    var sql = string.Format(insertSQL, uuid, jsonObj["DealFaultBillName"], jsonObj["FaultDesc"], jsonObj["PRODUCTBATCHNO"], jsonObj["PRODUCTNAME"], jsonObj["RecvFactoryName"], jsonObj["CreateDate"],
                        jsonObj["CreateEmployee"], jsonObj["isuse"], "0", jsonObj["RepairCount"], jsonObj["TransferStatus"], jsonObj["ISRETURN"], jsonObj["DealFaultType"], jsonObj["PRODUCTANDBATCH"], jsonObj["EngineNO"], jsonObj["EngineFamily"], jsonObj["MilitaryCheckStatus"], jsonObj["IsMilitaryCheck"]);
                    var sql2 = string.Format(insertSQL2, uuid, jsonObj["AuditempName"], jsonObj["audittime"], jsonObj["confirmempName"], jsonObj["confirmtime"], jsonObj["FromEmpName"], jsonObj["FromQty"], jsonObj["FromTime"], jsonObj["PageCount"], jsonObj["RequireFinishTime"], jsonObj["Notes"], jsonObj["pagecountfinish"]);
                    allUpdate = string.Format(allUpdate, sql, sql2);
                }
                var result = OracleHelper.ExecuteSql(allUpdate) > 0;
                rsLog.Info("MES开始处理五厂创建的排故JSON结果:" + (result ? "处理成功" : "处理失败"));
            }
            catch (Exception ex)
            {
                rsLog.Info("MES开始处理五厂创建的排故JSON:" + jsonData + " 异常：" + ex.Message);
            }
            finally
            {
                File.Delete(filepath);
            }
        }
        /// <summary>
        /// 处理5厂排故完成信息【返件完成】
        /// </summary>
        public void DealFiveDealFaultBillFinishData(string jsonData, string filepath)
        {
            try
            {
                rsLog.Info("MES开始处理五厂的排故完成JSON:【" + jsonData + "】");
                var json = JsonConvert.DeserializeObject(jsonData);
                var jsonObj2 = JsonConvert.DeserializeObject<Dictionary<string, object>>(json.ToString());
                var jsonObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonObj2["BSDATA"].ToString());
                var dt = OracleHelper.QueryTable(string.Format(@"select * from DEALFAULTBILL where dealfaultbillname='{0}' and isuse=0", jsonObj["DealFaultBillName"]), null);
                if (dt.Rows.Count == 0)
                {
                    rsLog.Info("MES查询不到五厂的排故完成排故单【" + jsonObj["DealFaultBillName"] + ""); return;
                }
                var updateSQL = @"update DEALFAULTBILLTRANSFER set revrejectempid=nvl((select employeeid from employee where employeename='{0}'),'{0}'),revrejectdate=to_date('{1}','yyyy-MM-dd hh24:mi:ss'),recreturnrejectreason='{2}'
                    ,acceptteamid=nvl((select employeeid from employee where employeename='{3}'),'{3}'),accepttime=to_date('{4}','yyyy-MM-dd hh24:mi:ss') where dealfaultbillid='{5}';";

                updateSQL = string.Format(updateSQL, jsonObj["Revreturnrejectname"], jsonObj["Revreturnrejecttime"], jsonObj["revreturnrejectreason"], jsonObj["Receivename"], jsonObj["receivetime"], dt.Rows[0]["dealfaultbillid"]);
                //返件完成--【完成拒绝状态，0未拒绝，1拒绝接收】表示拒绝接收，则更新状态为返件返出
                var revreturnrejectStatus = jsonObj["revreturnrejectStatus"].ToString();
                var updateWriteToOtherSystem = revreturnrejectStatus.Equals("1") ? string.Format(@"update WriteToOtherSystem set parentid=parentid||'_Five' where parentid='{0}' and RECORDTYPE='pushFiveFactoryStatusData' and ISSUCCESS='5';", dt.Rows[0]["dealfaultbillid"]) : "";
                var sql = string.Format(@"update DEALFAULTBILL set Transferstatus='{1}' where dealfaultbillid='{0}';", dt.Rows[0]["dealfaultbillid"], revreturnrejectStatus.Equals("1") ? 5 : 7);
                var allUpdate = string.Format(@"begin {0} {1} {2} end;", updateSQL, sql, updateWriteToOtherSystem);
                var result = OracleHelper.ExecuteSql(allUpdate) > 0;
                rsLog.Info("MES开始处理五厂的排故完成JSON结果:" + (result ? "处理成功" : "处理失败"));
            }
            catch (Exception ex)
            {
                rsLog.Info("MES开始处理五厂的排故完成JSON:" + jsonData + " 异常：" + ex.Message);
            }
            finally
            {
                File.Delete(filepath);
            }
        }
        #endregion

        #region 推送5厂排故信息
        public void PushFiveDealFaultBillJsonData()
        {
            var dt = OracleHelper.QueryTable(string.Format(@"select * from writetoothersystem w where w.issuccess=0 and w.recordtype LIKE 'LYDL%'"), null);
            foreach (DataRow row in dt.Rows)
            {
                try
                {
                    string absolutePath = AppDomain.CurrentDomain.BaseDirectory + "files\\";
                    if (!Directory.Exists(absolutePath))
                    {
                        Directory.CreateDirectory(absolutePath);
                    }
                    string jsonStr = row["sendXml"].ToString();
                    string filename = string.Format("{0}.json", row["parentid"].ToString());
                    string filePath = absolutePath + filename;
                    File.WriteAllText(filePath, jsonStr, new UTF8Encoding(false));
                    /*设置推送头部参数*/
                    HeadEntity head = GetHeadEntity(row["recordtype"].ToString());
                    head.FileName = filePath;
                    /*开始推送*/
                    LogHelp.WriteLog(string.Format("推送排故返件接口（机加MES→脉动线系统）【接口】开始上传文件【{0}】", filename));
                    var result = "";//HttpUtils.uploadFile(fileUploadUrl, head);
                    /*推送返回结果处理*/
                    LogHelp.WriteLog(string.Format("【推送排故返件接口（机加MES→脉动线系统）接口】文件上传返回结果：{0}", result));
                    var updateSql = string.Format(@"update writetoothersystem w set w.issuccess=1,w.resxml='{3}' where w.parentid='{0}' and recordtype='{1}' and productname='{2}'", row["parentid"].ToString(), row["recordtype"].ToString(), row["productname"].ToString(),result);
                    OracleHelper.ExecuteSql(updateSql);
                    /*删除推送数据*/
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
                catch (Exception ex)
                {
                    LogHelp.WriteLog(string.Format("推送排故返件接口（机加MES→脉动线系统）【接口】开始上传文件异常【{0}】", ex.Message));
                    continue;
                }
            }

        }
        #endregion

        #region 推送5厂问题快反类型 add by zhangrj 20251105
        /// <summary>
        /// 推送问题快反类型给5厂 add by zhangrj 20251105
        /// </summary>
        private void SendToFiveProblemType()
        {
            /*查询问题快反的类型表并推送*/
            string sql = string.Format(@"SELECT bo.id FROM BO_EU_MES_PROBLEM_TYPE bo 
                                  WHERE bo.factoryname = '装配厂'
                                  AND NOT EXISTS(SELECT 1 FROM sync_tablechangerecord st
                                    LEFT JOIN sync_sendtoappid so ON so.parentid = st.id 
                                    WHERE st.tablename = UPPER('BO_EU_MES_PROBLEM_TYPE') AND st.uniquecolvalue = bo.id AND so.toappid = '{0}')", toAppId_FIVE);
            DataTable dtProblemType = OracleHelper.QueryTable(sql, null);
            CommonMethods.InsertTableChangeRecord(dtProblemType, "BO_EU_MES_PROBLEM_TYPE", "id", toAppId_FIVE, CommonMethods.OpType.新增);
        }
        #endregion

        HeadEntity GetHeadEntity(string type)
        {
            HeadEntity head = new HeadEntity();
            head.Formappid = fromAppId;//来源appid
            head.Toappid = toAppId_FIVE;//目标appid
            head.Bstype = type;
            head.BsData = "";
            head.WenJianQiCaoRen = "刘美美";
            head.QianFaRen = "刘美美";
            head.ShenPiRen = "刘美美";
            return head;
        }

    }
}
